# coding=utf-8

import json

from django.db import transaction
from django.http import JsonResponse, HttpResponse
from lib.loginout import logout_sys
from ratelimit.decorators import ratelimit
from project.settings_common import NB_PROXY

from apps.baselogic.handlers.student import BaseHandler
from apps.baselogic.handlers.etc import handle_change_phone_send_sms_vcode
from apps.student.share import app_logger
from services.datamodel.common.models import UserOperations_StudentSelfChangeClass
from services.datamodel.integral.models import mm_StudentBalanceRecord
from services.datamodel.product.models import mm_ProductUse, mm_ProductPurchase
from services.datamodel.schoolclass.models import mm_Class
from services.datamodel.student.models import mm_Student
from services.datamodel.teacher.models import mm_Teacher


class Handler(BaseHandler):

    def __init__(self):
        BaseHandler.__init__(self,app_logger)

        self.METHOD_TAB = {
            'GET' : {
                'getmyinfo': self.handle_get_my_detail_info,
                'getmybasicinfo': self.handle_get_my_basic_info,
                'change_phone_send_sms_vcode': self.handle_change_phone_send_sms_vcode,
                'get_all_persion_in_class': self.handle_get_all_person_in_class,
                'get_student_parents_info': self.handle_get_student_parents_info,
                'get_student_balance': self.handle_get_student_balance_list
            },

            'PUT' : {
                'modify': self.handle_modify,
                'changeuserpassword': self.handle_change_userpassword,
                'changemyclass': self.handle_change_my_class,
            },

            #'DELETE' : self.handle_delete
        }

    @ratelimit(key='ip', rate='3/3m')
    def handle_change_phone_send_sms_vcode(self, request):

        self.checkMandatoryParams(request, ['phone'])
        if getattr(request, 'limited', False):
            return JsonResponse({'retcode': 1, 'msg': '操作过快, 稍后再试'})

        # 学生手机号唯一
        phone_number = request.param_dict['phone']
        mm_Student.is_unique_phonenumber_in_students(phone_number, is_raise=True)
        return handle_change_phone_send_sms_vcode(request)


    def handle_change_userpassword(self, request):

        self.app_logger.debug("handle_change_userpassword")

        self.checkMandatoryParams(request,['oldpassword','newpassword'])

        param_dict = request.param_dict

        studentid = request.session['studentid']


        ret = mm_Student.changePasswordByStudent(studentid,
                                                 param_dict['oldpassword'],
                                                 param_dict['newpassword'])

        # logout_sys(request)

        return JsonResponse(ret)

    def handle_change_my_class(self,request):
        self.app_logger.info("student change his class, student id %s" % request.session['studentid'])

        self.checkMandatoryParams(request,['invitecode'])

        param_dict = request.param_dict
        studentid = request.session['studentid']
        student = mm_Student.get_or_default(id=studentid, is_raise=True, msg_raise="学生不存在")

        if UserOperations_StudentSelfChangeClass.getOpCounts_StudentChangedClassBySelf_Today(request.user.id) >= 2:
            return JsonResponse({'retcode': 8, 'msg': "改变班级操作每天最多2次"})

        invit_code = param_dict['invitecode']

        if invit_code == NB_PROXY.invitecode:
            mm_Student.filter(id=studentid).update(proxy_id=NB_PROXY.proxy_id)
            mm_ProductPurchase.trial_all_product(student.user_id)
            return JsonResponse({'schoolname': None, 'gradename': None, 'classname': None, 'retcode': 0,
                                 'school_id': 0, 'grade_id': 0, 'class_id': 0})

        try:

            with transaction.atomic():
                # select_for_update will lock rows until the end of the transaction
                classObj = mm_Class.select_for_update().get(invitecode=invit_code)

                classid = classObj.id
                schoolid = classObj.school_id
                gradeid = classObj.grade_id
                currentClassId = student.classid

                if currentClassId == classid:
                    return JsonResponse({'retcode': 7, 'msg': "您要进入的班级就是您当前所在班级" })

                studentCount = mm_Student.getStudentNumberInClass(classObj.id)
                if studentCount >= classObj.studentlimit:
                    return JsonResponse({'retcode': 6, 'msg': "您要进入的班级已经达到人数上限" })

                ret = mm_Student.changeClass(studentid, classid, schoolid, gradeid)

                if ret['retcode'] == 0:
                    desc = "new classid:%s, schoolid:%s, gradeid:%s;old classid:%s" % (classid, schoolid, gradeid, currentClassId)
                    UserOperations_StudentSelfChangeClass.addOp_StudentChangedClassBySelf(request.user.id,
                                                                                          classid,
                                                                                          desc)
                    # 修改班級之後更新session['classid']
                    request.session['schoolid'] = schoolid
                    request.session['gradeid'] = gradeid
                    request.session['classid'] = classid

        except mm_Class.model.DoesNotExist:
            return JsonResponse({'retcode': 5, 'msg': "您输入的班级邀请码不存在"})

        #task:912,返回信息增加学校/年级/班级名称
        ret.update({'schoolname': classObj.school.name, 'gradename': classObj.grade.name, 'classname': classObj.name,
                    'school_id': classObj.school_id, 'grade_id': classObj.grade_id, 'class_id': classObj.id})
        return JsonResponse(ret)

    def handle_modify(self, request):

        studentid = request.session['studentid']


        ret = mm_Student.modifyStudentByHimself(studentid,request)

        return JsonResponse(ret)

    def handle_get_my_basic_info(self, request):
        self.is_not_zero_int_params(request, ['student_id'])
        student_id = int(request.param_dict.get('student_id', 0))

        studentid = student_id if student_id else request.session['studentid']

        self.app_logger.debug(
            "handle_get_my_basic_info, student id: %s" % studentid)

        ret, info = mm_Student.getBasicInfo(studentid)
        if not ret:
            return JsonResponse({
                'retcode': 1,
                'msg': info
            })

        response = {
            'retcode': 0,
            'basicInfo' :info
        }

        return HttpResponse(
            json.dumps(response),
            content_type='application/json')

    def handle_get_my_detail_info(self, request):

        studentid = request.session['studentid']

        self.app_logger.debug(
            "handle_get_my_detail_info, student id: {}.".format(studentid))

        ret = mm_Student.getDetailInfo(studentid)

        if ret['retcode'] == 0 and ret['classid']:
            ret["teacherlist"] = mm_Teacher.getTeachersInClass(ret["classid"]).get('retlist',[])

        return JsonResponse(ret)

    def handle_get_all_person_in_class(self, request):

        """
        curl --cookie "sessionid=0tggs03f808fcdqn39na2h6096myyb9b" "http://127.0.0.1:8000/api/student/mobile/yj_students/?action=get_all_persion_in_class"
        :return:
        """
        classid = request.session["classid"]

        student_list = mm_Student.getStudentsInClasses([classid])
        student_uid_list = [student["user_id"] for student in student_list]

        yjmember_uids = list(mm_ProductUse.yijiao_member(student_uid_list).keys())
        teacher_list = mm_Teacher.getTeachersInClass(classid)["retlist"]
        class_info = mm_Class.get_class_info_by_id(classid)

        for student in student_list:
            student_uid = student["user_id"]
            isyjmember = False
            if student_uid in yjmember_uids:
                isyjmember = True
            student.update({"isyjmember": isyjmember})

        resp = {
            "retcode": 0,
            "classinfo": class_info,
            "allstudent": student_list,
            "allteacher": teacher_list,
        }

        return JsonResponse(resp)

    def handle_get_student_parents_info(self, request):
        return JsonResponse({'retcode':0, 'data': mm_Student.get_student_parents_info(request.user.id)})

    def handle_get_student_balance_list(self, request):
        self.checkMandatoryParams(request, ['page'])
        self.is_int_params(request, ['page'])
        uid = request.user.id
        page = int(request.param_dict['page'])
        balance = mm_Student.get_or_default(user_id=uid).balance
        ret = mm_StudentBalanceRecord.list_record(uid, page)
        ret.update({'balance': float(balance / 100)})
        return JsonResponse(ret)

student_handler = Handler()
